package cn.wolfcode.trip.base.service.impl;

import cn.wolfcode.trip.base.domain.User;
import cn.wolfcode.trip.base.mapper.UserMapper;
import cn.wolfcode.trip.base.query.QueryObject;
import cn.wolfcode.trip.base.service.IUserService;
import cn.wolfcode.trip.base.util.UserContext;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserServiceImpl implements IUserService {
    @Autowired
    private UserMapper userMapper;

    public void saveOrUpdate(User user) {
        if (user.getId() != null) {
            userMapper.updateByPrimaryKey(user);
        }else {
            //验证邮箱是否已存在
            User temp = userMapper.selectByEmailAndPassword(user.getEmail(),null);
            if (temp != null) {
                throw new RuntimeException("邮箱已注册!");
            }
            user.setGender(User.GENDER_SECRECY);
            user.setHeadImgUrl("/upload/6610317b-2077-4bd3-98c7-7d31b6613469.jpg");
            user.setCoverImgUrl("/upload/f58ec057-e58e-4351-974b-b1ac330009c1.jpeg");
            userMapper.insert(user);
        }
    }

    public User login(String email, String password) {
        if (email != null && password != null) {
            User user = userMapper.selectByEmailAndPassword(email, password);
            if (user == null) {
                throw new RuntimeException("账号或密码有误");
            }
            UserContext.setCurrentUser(user);
            return user;
        }
        throw new RuntimeException("邮箱或密码不能为空");
    }

    public PageInfo<User> query(QueryObject qo) {
        PageHelper.startPage(qo.getCurrentPage(), qo.getPageSize());
        List<User> list = userMapper.selectForList(qo);
        return new PageInfo<>(list);
    }

    public User selectById(Long id) {
        return userMapper.selectByPrimaryKey(id);
    }
}
